/**
 * 文件处理工具类
 * 
 * 核心功能：
 * - 模拟文件夹访问和文件读取
 * - 自动化文件处理和上传
 * - 文件类型识别和分类
 */

/**
 * 模拟打开指定设备文件夹并读取所有文件
 * @param {string} deviceName - 设备名称
 * @returns {Promise<Array>} 文件列表
 */
export const openDeviceFolder = async (deviceName) => {
  console.log(`模拟打开设备文件夹: C:\\Users\\YHNZ\\Downloads\\${deviceName}`)
  
  // 模拟文件夹访问延迟
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // 模拟文件夹中的文件
  const mockFiles = [
    {
      name: `${deviceName}_coordinates.txt`,
      type: 'coordinates',
      size: 2048,
      content: generateMockCoordinates(deviceName),
      lastModified: new Date(Date.now() - Math.random() * 86400000)
    },
    {
      name: `${deviceName}_logo.png`,
      type: 'logo',
      size: 15360,
      url: generateMockImageUrl(deviceName, 'logo'),
      lastModified: new Date(Date.now() - Math.random() * 86400000)
    },
    {
      name: `${deviceName}_interface_main.jpg`,
      type: 'interface',
      size: 51200,
      url: generateMockImageUrl(deviceName, 'main'),
      lastModified: new Date(Date.now() - Math.random() * 86400000)
    },
    {
      name: `${deviceName}_interface_settings.jpg`,
      type: 'interface',
      size: 48640,
      url: generateMockImageUrl(deviceName, 'settings'),
      lastModified: new Date(Date.now() - Math.random() * 86400000)
    },
    {
      name: `${deviceName}_interface_monitor.jpg`,
      type: 'interface',
      size: 53760,
      url: generateMockImageUrl(deviceName, 'monitor'),
      lastModified: new Date(Date.now() - Math.random() * 86400000)
    }
  ]
  
  console.log(`找到 ${mockFiles.length} 个文件:`, mockFiles.map(f => f.name))
  return mockFiles
}

/**
 * 生成模拟坐标数据
 * @param {string} deviceName - 设备名称
 * @returns {string} 坐标数据内容
 */
const generateMockCoordinates = (deviceName) => {
  const coordinates = [
    { id: 1, x: 100, y: 50, width: 80, height: 30, label: '开机', action: 'power_on' },
    { id: 2, x: 200, y: 50, width: 80, height: 30, label: '设置', action: 'settings' },
    { id: 3, x: 300, y: 50, width: 80, height: 30, label: '监控', action: 'monitor' },
    { id: 4, x: 100, y: 100, width: 120, height: 40, label: '开始测量', action: 'start_measure' },
    { id: 5, x: 250, y: 100, width: 120, height: 40, label: '停止测量', action: 'stop_measure' },
    { id: 6, x: 100, y: 160, width: 80, height: 30, label: '保存', action: 'save' },
    { id: 7, x: 200, y: 160, width: 80, height: 30, label: '导出', action: 'export' },
    { id: 8, x: 300, y: 160, width: 80, height: 30, label: '返回', action: 'back' }
  ]
  
  return JSON.stringify({
    device: deviceName,
    version: '1.0',
    created: new Date().toISOString(),
    coordinates: coordinates
  }, null, 2)
}

/**
 * 生成模拟图片URL
 * @param {string} deviceName - 设备名称
 * @param {string} type - 图片类型
 * @returns {string} 图片URL
 */
const generateMockImageUrl = (deviceName, type) => {
  const colors = {
    logo: '2196F3',
    main: '4CAF50',
    settings: 'FF9800',
    monitor: '9C27B0'
  }
  
  const color = colors[type] || '607D8B'
  const text = encodeURIComponent(`${deviceName}_${type}`)
  return `https://via.placeholder.com/800x600/${color}/ffffff?text=${text}`
}

/**
 * 处理文件上传
 * @param {Array} files - 文件列表
 * @returns {Promise<Object>} 处理结果
 */
export const processUploadedFiles = async (files) => {
  console.log('开始处理上传的文件:', files.length)
  
  const processedFiles = {
    images: [],
    coordinates: null,
    logos: [],
    others: []
  }
  
  for (const file of files) {
    switch (file.type) {
      case 'coordinates':
        processedFiles.coordinates = {
          name: file.name,
          content: file.content,
          url: `/mock/coordinates/${file.name}`
        }
        break
        
      case 'logo':
        processedFiles.logos.push({
          id: `logo_${Date.now()}`,
          name: file.name.replace(/\.[^/.]+$/, ""), // 移除扩展名
          url: file.url,
          thumbnail: file.url
        })
        break
        
      case 'interface':
        processedFiles.images.push({
          id: `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          name: file.name.replace(/\.[^/.]+$/, "").replace(/_/g, ' '), // 移除扩展名并格式化
          url: file.url,
          thumbnail: file.url
        })
        break
        
      default:
        processedFiles.others.push(file)
        break
    }
  }
  
  // 合并logo到images中
  processedFiles.images = [...processedFiles.logos, ...processedFiles.images]
  
  console.log('文件处理完成:', {
    images: processedFiles.images.length,
    coordinates: processedFiles.coordinates ? 1 : 0,
    others: processedFiles.others.length
  })
  
  return processedFiles
}

/**
 * 验证文件类型和大小
 * @param {File} file - 文件对象
 * @returns {boolean} 是否有效
 */
export const validateFile = (file) => {
  const maxSize = 5 * 1024 * 1024 // 5MB
  const allowedTypes = [
    'image/jpeg',
    'image/png',
    'image/gif',
    'text/plain',
    'application/json'
  ]
  
  if (file.size > maxSize) {
    console.warn(`文件 ${file.name} 超过大小限制 (${file.size} > ${maxSize})`)
    return false
  }
  
  if (!allowedTypes.includes(file.type)) {
    console.warn(`文件 ${file.name} 类型不支持 (${file.type})`)
    return false
  }
  
  return true
}

/**
 * 读取文件内容
 * @param {File} file - 文件对象
 * @returns {Promise<string>} 文件内容
 */
export const readFileContent = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      resolve(e.target.result)
    }
    
    reader.onerror = (e) => {
      reject(new Error(`读取文件失败: ${e.target.error}`))
    }
    
    if (file.type.startsWith('text/') || file.type === 'application/json') {
      reader.readAsText(file)
    } else {
      reader.readAsDataURL(file)
    }
  })
}

/**
 * 创建文件下载
 * @param {string} content - 文件内容
 * @param {string} filename - 文件名
 * @param {string} mimeType - MIME类型
 */
export const downloadFile = (content, filename, mimeType = 'text/plain') => {
  const blob = new Blob([content], { type: mimeType })
  const url = URL.createObjectURL(blob)
  
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  link.style.display = 'none'
  
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  URL.revokeObjectURL(url)
  console.log(`文件下载完成: ${filename}`)
}

/**
 * 格式化文件大小
 * @param {number} bytes - 字节数
 * @returns {string} 格式化后的大小
 */
export const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 获取文件扩展名
 * @param {string} filename - 文件名
 * @returns {string} 扩展名
 */
export const getFileExtension = (filename) => {
  return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2)
}

/**
 * 检查是否为图片文件
 * @param {string} filename - 文件名
 * @returns {boolean} 是否为图片
 */
export const isImageFile = (filename) => {
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']
  const ext = getFileExtension(filename).toLowerCase()
  return imageExtensions.includes(ext)
}

/**
 * 检查是否为坐标文件
 * @param {string} filename - 文件名
 * @returns {boolean} 是否为坐标文件
 */
export const isCoordinateFile = (filename) => {
  const coordinateExtensions = ['txt', 'log', 'json']
  const ext = getFileExtension(filename).toLowerCase()
  const nameContainsCoordinate = filename.toLowerCase().includes('coordinate') || 
                                  filename.toLowerCase().includes('坐标')
  return coordinateExtensions.includes(ext) && nameContainsCoordinate
}

export default {
  openDeviceFolder,
  processUploadedFiles,
  validateFile,
  readFileContent,
  downloadFile,
  formatFileSize,
  getFileExtension,
  isImageFile,
  isCoordinateFile
}
